package com.jdk.learn.nio._04;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Scanner;

/**
 * Created by ricky
 * on 2018/2/11.
 * <p>
 * UDP方式的网络IO
 */
public class TestNetUDP {

    @Test
    public void client() {
        DatagramChannel dc= null;
        try {
            dc= DatagramChannel.open();
            dc.configureBlocking(false);
            ByteBuffer buf=ByteBuffer.allocate(1024);
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String str=scanner.next();
                buf.put((LocalDateTime.now().toString()+":\n"+str).getBytes());
                buf.flip();//切换到读
                dc.send(buf,new InetSocketAddress("127.0.0.1",9999));
                buf.clear();
            }
            scanner.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void server() {
        DatagramChannel dc= null;
        try {
            dc= DatagramChannel.open();
            dc.configureBlocking(false);
            dc.bind(new InetSocketAddress(9999));
            Selector selector = Selector.open();
            dc.register(selector, SelectionKey.OP_READ);
            while (selector.select()>0) {
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    if (key.isReadable()) {
                        ByteBuffer buf=ByteBuffer.allocate(1024);
                        dc.receive(buf);
                        buf.flip();

                        System.out.println(new String(buf.array(),0,buf.limit()));
                        buf.clear();
                    }
                    it.remove();
                }
            }




        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
